package com.youhome.wechat.controller;

import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.common.response.ResultPage;
import com.youhome.service.model.BUser;
import com.youhome.service.model.HouseFavourite;
import com.youhome.service.model.ListHub;
import com.youhome.service.model.ListHubList;
import com.youhome.service.service.BUserService;
import com.youhome.service.service.HouseFavouriteService;
import com.youhome.service.service.ListHubService;
import com.youhome.service.service.TokenService;
import com.youhome.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by chen365 on 2018/06/27.
 */
@RestController
@RequestMapping(value = "/favourite")
@Api(tags = "收藏")
public class FavouriteController {

    @Autowired
    private ListHubService listHubService;
    @Autowired
    private BUserService userService;
    @Autowired
    private HouseFavouriteService houseFavouriteService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "收藏/取消房源", notes = "收藏/取消房源", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "action", value = "save/unsave", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "houseId", required = true, paramType = "path")
    })
    @PostMapping(value = "/{action}/{houseId}")
    public Object saveFavorite(HttpServletRequest request, @PathVariable String action, @PathVariable String houseId) throws CustomException {
        BUser user = tokenService.getUserByToken(request);
        houseFavouriteService.saveFavorite(user, action, houseId);
        return new Result(ResultCode.SUCCESS);

        /*
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        BUser user = userService.getCurrentUser(openid);
        //判断手机号是否已经注册
        if (user == null) {
            return new Result<>(ResultCode.IS_BINDING_PHONE);
        }
        try {
            ListHub house = listHubService.selectByPrimaryKey(houseId);

            if (house == null)
                return new Result(ResultCode.ILLEGAL_OPERATION);

            HouseFavourite record = new HouseFavourite();
            record.setHouseId(houseId);
            record.setUserId(user.getUserId());
            HouseFavourite favourite = houseFavouriteService.selectByHouseIdAndUserId(record);
            houseFavouriteService.saveFavorite(user,action,houseId);
            if (action.equalsIgnoreCase("save")) {
                if (favourite != null) {
                    return new Result(ResultCode.HAVE_FAVOURITE);
                } else {
                    if (houseFavouriteService.insert(record) > 0) {
                        return new Result(ResultCode.SUCCESS);
                    }
                }
            } else if (action.equalsIgnoreCase("unsave")) {
                if (favourite != null) {
                    if (houseFavouriteService.deleteByPrimaryKey(favourite.getId()) > 0) {
                        return new Result(ResultCode.SUCCESS);
                    }
                } else {
                    return new Result(ResultCode.NOT_FAVOURITE);
                }
            } else {
                return new Result(ResultCode.FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.FAIL);

        */
    }

    @ApiOperation(value = "收藏列表", notes = "收藏列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "pageNumber", value = "页码", required = true, paramType = "path"),
    })
    @GetMapping(value = "/{pageNumber}")
    public Object list(HttpServletRequest request, @PathVariable("pageNumber") Integer pageNumber) throws CustomException {


        /*
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        BUser user = userService.getCurrentUser(openid);
        //判断手机号是否已经注册
        if (user == null) {
            return new Result<>(ResultCode.IS_BINDING_PHONE);
        }

        */

        BUser user = tokenService.getUserByToken(request);

        if (StringUtils.isEmpty(pageNumber))
            return new Result(ResultCode.ERROR_PARAMETER);

        Integer pageSize = 10;
        PageInfo<ListHubList> pageInfo = listHubService.selectFavouriteHouseByUserId(pageNumber, pageSize, user.getUserId());
        return new ResultPage<>(ResultCode.SUCCESS, pageInfo);
    }

    @ApiOperation(value = "收藏房源ID列表", notes = "收藏房源ID列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/house-id")
    public Object houseId(HttpServletRequest request) throws CustomException {


        /*
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        BUser user = userService.getCurrentUser(openid);
        //判断手机号是否已经注册
        if (user == null) {
            return new Result<>(ResultCode.IS_BINDING_PHONE);
        }

        */

        BUser user = tokenService.getUserByToken(request);
        List<String> list = houseFavouriteService.selectHouseIdByUserId(user.getUserId());
        return new Result(ResultCode.SUCCESS, list);
    }
}
